package com.roosterrobotics.replicant;

import com.roosterrobotics.replicant.provider.ReplicantData;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class DeviceCursorAdapter extends CursorAdapter {
	
	private LayoutInflater mLayoutInflater;

	public DeviceCursorAdapter(Context context, Cursor c) {
		super(context, c);
		mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

	}

	public DeviceCursorAdapter(Context context, Cursor c, boolean autoRequery) {
		super(context, c, autoRequery);
		mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	
	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		String name = cursor.getString(cursor.getColumnIndex(ReplicantData.Devices.DEVICE_NAME_COLUMN_NAME));
		String address = cursor.getString(cursor.getColumnIndex(ReplicantData.Devices.DEVICE_ADDRESS_COLUMN_NAME));
		Long port = cursor.getLong(cursor.getColumnIndex(ReplicantData.Devices.DEVICE_PORT_COLUMN_NAME));
		boolean lock = cursor.getInt(cursor.getColumnIndex(ReplicantData.Devices.DEVICE_LOCK_COLUMN_NAME)) > 0;
		boolean replicant = cursor.getInt(cursor.getColumnIndex(ReplicantData.Devices.DEVICE_REPLICANT_COLUMN_NAME)) > 0;
		TextView devName = (TextView) view.findViewById(R.id.deviceText);
		TextView devAddress = (TextView) view.findViewById(R.id.deviceAddressText);
		ImageView devIcon = (ImageView) view.findViewById(R.id.lockIcon);
		TextView devReplicant = (TextView) view.findViewById(R.id.deviceReplicant);
		
		devName.setText(name);
		devAddress.setText(address + ":" + String.valueOf(port));
		if (lock) {
			devIcon.setImageResource(R.drawable.lock);
		}
		else {
			devIcon.setImageResource(R.drawable.lockopen);
		}
		if (replicant) {
			devReplicant.setText(R.string.replicant);
			devReplicant.setVisibility(View.VISIBLE);
		}
		else {
			devReplicant.setVisibility(View.INVISIBLE);
		}
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		return mLayoutInflater.inflate(R.layout.devices_row, null);
	}

}
